package com.nine.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nine.anno.MyRedisCache;
import com.nine.constant.UserConstant;
import com.nine.entity.User;
import com.nine.mapper.UserMapper;
import com.nine.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<User> findAll() {

        Object result = redisTemplate.opsForValue().get(UserConstant.userAll);
        if (result != null) {
            return (List<User>) result;
        }

        List<User> users = baseMapper.selectList(null);
        if (CollectionUtils.isEmpty(users)) {
            // 查询到数据，放到缓存，2s后过期
            redisTemplate.opsForValue().set(UserConstant.userAll, null, 2, TimeUnit.SECONDS);
        } else {
            // 查询到数据，放到缓存
            redisTemplate.opsForValue().set(UserConstant.userAll, users);
        }
        return users;
    }

    @Override
    @MyRedisCache(key = "userlist")
    public List<User> findAllByAnno() {
        return baseMapper.selectList(null);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId 用户id，同时传递给占位符中
     * @return
     */
    @Override
    @MyRedisCache(key = "user", match = "#userId", expire = 60)
    public User findUserById(Long userId) {
        return baseMapper.selectById(userId);
    }
}
